//
//  PhotoBrowserAnimator.swift
//  ImageBrowse
//
//  Created by zs on 16/6/20.
//  Copyright © 2016年 zs. All rights reserved.
//

import UIKit

class PhotoBrowserAnimator: NSObject {
  var isPresented : Bool = false
}
// MARK:- 实现UIViewControllerTransitioningDelegate协议中的方法
extension PhotoBrowserAnimator : UIViewControllerTransitioningDelegate {
    func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        isPresented = true
        
        return self
        
    }
    func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        
        isPresented = false
        
        return self
    }
    
}

extension PhotoBrowserAnimator : UIViewControllerAnimatedTransitioning {
    func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval {
        return 2.0
    }
    
    func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
        isPresented ? animationForPresentView(transitionContext) : animationForDismissView(transitionContext)
    }
    
    func animationForPresentView(transitionContext: UIViewControllerContextTransitioning) {
        // 1.获取containerView的容器的View
        let containerView = transitionContext.containerView()
        
        // 2.弹出的View, UITransitionContextToViewKey : 获取到弹出的View
        let presentedView = transitionContext.viewForKey(UITransitionContextToViewKey)!
        containerView?.addSubview(presentedView)
        
        // 3.执行渐变动画
        presentedView.alpha = 0.0
        UIView.animateWithDuration(transitionDuration(transitionContext), animations: { () -> Void in
            presentedView.alpha = 1.0
        }) { (finished : Bool) -> Void in
            transitionContext.completeTransition(true)
        }
    }
    
    func animationForDismissView(transitionContext: UIViewControllerContextTransitioning) {
        // 1.获取消失的View
        let dismissedView = transitionContext.viewForKey(UITransitionContextFromViewKey)!
        
        // 2.执行动画
        UIView.animateWithDuration(transitionDuration(transitionContext), animations: { () -> Void in
            dismissedView.alpha = 0.0
        }) { (finished : Bool) -> Void in
            dismissedView.removeFromSuperview()
            transitionContext.completeTransition(true)
        }
    }
}
